package com.example.demo.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.demo.MyApplication;
import com.example.demo.R;

/**
 * @author: xtxiaolu
 * @date: 2023/7/12
 * 描述:
 */
public class ToastUtil {
    private static Toast sToast;
    private static Handler sHandler = new Handler(Looper.getMainLooper());

    public static void showShort(String message) {
        showToast(MyApplication.getInstance(), message, Toast.LENGTH_SHORT);
    }

    public static void showLong(String message) {
        showToast(MyApplication.getInstance(), message, Toast.LENGTH_LONG);
    }

    private static void showToast(Context context, String message, int duration) {
        cancelToast();
        sHandler.post(() -> {
            View toastView = LayoutInflater.from(context).inflate(R.layout.toast_layout, null);
            TextView textView = toastView.findViewById(R.id.toastText);
            textView.setText(message);

            sToast = new Toast(context);
            sToast.setGravity(Gravity.CENTER, 0, 0);
            sToast.setDuration(duration);
            sToast.setView(toastView);
            sToast.show();
        });
    }

    public static void cancelToast() {
        if (sToast != null) {
            sToast.cancel();
            sToast = null;
        }
    }
}
